//
//  SegmentItemTitleDataSource.swift
//  PageNavigator
//
//  Created by 张奇 on 2025/8/14.
//

import UIKit
import Foundation

public class SegmentItemTitleDataSource: SegmentItemDataSource {
    
    private let titles: [String]
    /// label的numberOfLines
    public var titleNumberOfLines: Int = 1
    /// title普通状态的textColor
    public var titleNormalColor: UIColor = .black
    /// title选中状态的textColor
    public var titleSelectedColor: UIColor = .red
    /// title普通状态时的字体
    public var titleNormalFont: UIFont = UIFont.systemFont(ofSize: 15)
    /// title选中时的字体
    public var titleSelectedFont: UIFont = UIFont.systemFont(ofSize: 15)
   
    private var itemContentSizeCache: [Int: CGSize] = [:]
                
    public init(titles: [String]) {
        self.titles = titles
    }

    private var textAttributes: [UInt: [NSAttributedString.Key: Any]] = [:]
    private var widthCaches: [Int: CGFloat] = [:]
    
    override func calculateSegmentItemContentSize(at index: Int) -> CGSize {
        let title = titles[index]
        let size = NSString(string: title).boundingRect(with: CGSize(width: CGFloat.infinity, height: CGFloat.infinity), options: [.usesFontLeading, .usesLineFragmentOrigin], attributes: [NSAttributedString.Key.font : titleNormalFont], context: nil).size
        return CGSize.init(width: round(size.width), height: round(size.height))
    }
    
    private func isAutomaticCalculateWidth() -> Bool {
        return itemWidth == VIEW_AUTOMATIC_DIMENSION
    }
    
    public override func getRegisterCellClass() -> AnyClass {
        return SegmentItemTitleCell.self
    }
    
    public override func numberOfItems(in content: SegmentViewController) -> Int {
        return titles.count
    }
    
    public override func segmentViewController(_ content: SegmentViewController, associatedDataForItemAt index: Int) -> Any {
        return titles[index]
    }
    
    public override func segmentViewController(_ content: SegmentViewController, sizeForItemAt index: Int) -> CGSize {
        if isAutomaticCalculateWidth() {
            let contentSize = segmentViewController(content, contentSizeForItemAt: index)
            return CGSize(width: contentSize.width, height: itemHeight)
        }
        return CGSize(width: itemWidth, height: itemHeight)
    }
    
    public override func segmentViewController(_ content: SegmentViewController, contentSizeForItemAt index: Int) -> CGSize {
        if let size = itemContentSizeCache[index] {
            return size
        }
        
        let size = calculateSegmentItemContentSize(at: index)
        itemContentSizeCache[index] = size
        return size
    }

}
